package com.example.gemfire.resources;

import com.example.gemfire.domain.Card;
import com.example.gemfire.repository.CardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/cards")
public class CardController {

    @Autowired
    private CardRepository cardRepository;

    @GetMapping("")
    public HttpEntity<List<Card>> getAll() {
        List<Card> cardList = (List<Card>) cardRepository.findAll();
        if(cardList.size() == 0) {
            return new ResponseEntity<>((List<Card>) null, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(cardList, HttpStatus.OK);
    }

    @GetMapping("/{key}")
    public HttpEntity<Card> getByKey(
            @PathVariable(value = "key") String key) {
        Card card = cardRepository.findByKey(key);
        return new ResponseEntity<>(card, card == null ? HttpStatus.NOT_FOUND : HttpStatus.OK);
    }

    @GetMapping("/value/{key}")
    public HttpEntity<String> getValueByKey(
            @PathVariable(value = "key") String key) {
        Card card = cardRepository.findByKey(key);
        if(card == null || card.getValue() == null) {
            return new ResponseEntity<>("", HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(card.getValue(), HttpStatus.OK);
    }

    @PostMapping("")
    public HttpEntity<Card> add(
            @RequestBody Card card
    ) {
        if(card.getKey() == null) {
            return new ResponseEntity<>((Card) null, HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(cardRepository.save(card), HttpStatus.CREATED);
    }

    @PutMapping("")
    public HttpEntity<Card> update(
            @RequestBody Card card
    ) {
        if(card.getKey() == null) {
            return new ResponseEntity<>((Card) null, HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(cardRepository.save(card), HttpStatus.OK);
    }

    @DeleteMapping("/{key}")
    public HttpEntity<Object> deleteByKey(
            @PathVariable(value = "key") String key) {
        cardRepository.deleteById(key);
        return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
    }

    @DeleteMapping("")
    public HttpEntity<Object> deleteAll() {
        cardRepository.deleteAll();
        return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
    }


}
